#!/bin/bash
set -euo pipefail

# Change directory to the root of the project
cd "$(dirname "$0")/.."

# Use debug logging by default
export RUST_LOG="${RUST_LOG:-debug}"

# Default to a self-signed certificate
# TODO automatically generate if it doesn't exist.
CERT="${CERT:-dev/localhost.crt}"
KEY="${KEY:-dev/localhost.key}"

# Default to listening on localhost:4443
HOST="${HOST:-[::]}"
PORT="${PORT:-4443}"
LISTEN="${LISTEN:-$HOST:$PORT}"

# A list of optional args
ARGS=""

# Connect to the given URL to get origins.
# TODO default to a public instance?
if [ -n "${API-}" ]; then
	ARGS="$ARGS --api $API"
fi

# Provide our node URL when registering origins.
if [ -n "${NODE-}" ]; then
	ARGS="$ARGS --api-node $NODE"
fi

echo "Publish URL: https://quic.video/publish/?server=localhost:${PORT}"

# Run the relay and forward any arguments
cargo run --bin moq-relay -- --listen "$LISTEN" --tls-cert "$CERT" --tls-key "$KEY" --dev $ARGS -- "$@"
